import socket
import tcp_add_pb2
import datetime

def all_bytes():
    person = tcp_add_pb2.Person()
    person.name = send_name
    person.time = send_time
    person.show = send_show
    # 序列化
    return person.SerializeToString()

if __name__ == '__main__':
    # 1.创建tcp服务端套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    # 2.绑定端口号

    tcp_server_socket.bind(("", 9090))
    # 3.设置监听

    tcp_server_socket.listen(128)
    # 4.等待接收客户端的连接请求

    new_client, ip_port = tcp_server_socket.accept()

    print("端口号",ip_port)
    # 5.接收客户端数据
    # 收发信息都使用新的套接字
    while True:
        # 接收信息
        Head_data = new_client.recv(1024)
        tmessage = tcp_add_pb2.Person()
        # 将信息反序列化
        tmessage.ParseFromString(Head_data)
        m_name = tmessage.name
        m_time = tmessage.time
        m_show = tmessage.show
        print(f'姓名:{m_name}在{m_time}时说{m_show}')

        send_name = input("姓名")
        send_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        send_show = input("说:")
        hearBeat_data = all_bytes()
        # 3.将数据发送到服务端
        new_client.send(hearBeat_data)
        # 4.接收服务端的数据
    # 关闭服务端和客户端的套接字,表示和客户端停止通信
    new_client.close()
    # 7.关闭服务端套接字,表示不再等待接收客户端的连接请求
    tcp_server_socket.close()